<?php
namespace common\components;
use Yii;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云对象存储功能
 * Class Aliyunoss
 * @package common\components
 */
class Aliyunoss
{
    public $accessKeyId;
    public $accessKeySecret;
    public $endpoint;
    public $bucket;
    public $ossClient;

    public function __construct($bucket){
        //获取阿里云oss的accessKeyId
        $this->accessKeyId = Yii::$app->params['oss']['accessKeyId'];
        //获取阿里云oss的accessKeySecret
        $this->accessKeySecret = Yii::$app->params['oss']['accessKeySecret'];
         //获取阿里云oss的endPoint
        $this->endpoint = Yii::$app->params['oss']['endPoint'];
        $this->bucket = $bucket;
        //实例化OssClient对象
        try {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * 创建存储空间
     *
     * @param $bucket
     * 空间名称
     *
     * @return null|string
     */
    public function createBucket($bucket){
        try {
            return $this->ossClient->createBucket($bucket);
        } catch (OssException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 存储字符
     *
     * @param $object
     * 存储路径
     *
     * @param $content
     * 存储内容
     *
     * @return null|string
     */

    public function putObject($object,$content){
        try {
            return $this->ossClient->putObject($this->bucket, $object, $content);
        } catch (OssException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 删除单个存储对象
     * @param $object
     * 对象路径
     *
     * @return null|string
     */
    public function deleteObject($object){
        try {
            return $this->ossClient->deleteObject($this->bucket, $object);
        } catch (OssException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 删除多个存储对象
     * @param array $objects
     * 多个存储对象路径数组
     *
     * @return \OSS\Http\ResponseCore|string
     */
   function deleteObjects(array $objects)
    {
        try{
            return $this->ossClient->deleteObjects($this->bucket, $objects);
        } catch(OssException $e) {
            return $e->getMessage();
        }
    }

    function doesBucketExist($bucket)
    {
        try {
            $res = $this->ossClient->doesBucketExist($bucket);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        if ($res === true) {
            return true;
        } else {
            return false;
        }
    }

    function doesObjectExist($object)
    {
        try{
            $exist = $this->ossClient->doesObjectExist($this->bucket, $object);
        } catch(OssException $e) {
            return $e->getMessage();
        }
        return $exist;
    }

    /**
     * 上传文件
     * @param $object
     * 上传到阿里云oss 路径 即key值
     *
     * @param $filePath
     * 上传文件的本地绝对路径
     *
     * @return null|string
     */
    function uploadFile($object,$filePath)
    {
        try{
            return $this->ossClient->uploadFile($this->bucket, $object, $filePath);
        } catch(OssException $e) {
            return $e->getMessage();
        }
    }


    /**
     * 上传base64格式的图片到阿里云oss
     *
     * @param $base64String
     * 图片转成的base64字符串，多个图片之间用 sign 隔开
     *
     * @param $prefix
     * 传到阿里云的图片目录名称
     *
     * @param int $limit_count
     * 限制图片上传数量
     *
     * @param int $flag
     * 是否计算图片长宽 1返回长宽，0不需要
     * @param string $sign
     * 多图片切割标记
     *
     * @return array
     */
    static function uploadBase64Files($base64String, $prefix, $sign, $limit_count = 9, $flag = 1)
    {
        $photos = array_values(array_filter(explode($sign, $base64String)));
        $path_vales = array();
        foreach ($photos as $key => $photo) {
            if ($key > $limit_count - 1) {
                break;
            }
            if(strpos($photo,'http://')!==false||strpos($photo,'https://')!==false){
                if ($flag == 1) {
                    $imgInfo = getimagesize($photo);
                    $result = array('full_path' => $photo, 'path' => substr($photo, 51), 'img_width' => $imgInfo[0], 'img_height' => $imgInfo[1]);
                } else {
                    $result = array('full_path' => $photo, 'path' => substr($photo, 51));
                }
                array_push($path_vales, $result);
                continue;
            }

            $location = 'uploads/' . time() . rand(1, 10000) . '.png';
            file_put_contents($location, base64_decode($photo));
            $alicos_path = $prefix.'/'.date('YmdHis').mt_rand(10000,99999).'.png';
            $alicos = (new Aliyunoss('gstationpublic'))->uploadFile($alicos_path, $location);
            $path = $alicos['info']['url'];
            if ($flag == 1) {
                $imgInfo = getimagesize($location);
                $result = array('full_path' => $path, 'path' => substr($path, 51), 'img_width' => $imgInfo[0], 'img_height' => $imgInfo[1]);
            } else {
                $result = array('full_path' => $path, 'path' => substr($path, 51));
            }
            array_push($path_vales, $result);
            @unlink($location);
        }
        return $path_vales;
    }
    static function uploadBase64File($base64String, $prefix, $flag = 0)
    {
        $location = 'uploads/' . time() . rand(1, 10000) . '.jpg';
        file_put_contents($location, base64_decode($base64String));
        $alicos_path = $prefix . '/' . date('Ymd') . uniqid(mt_rand(10000, 99999)) . '.jpg';
        $alicos = (new Aliyunoss('gstationpublic'))->uploadFile($alicos_path, $location);

        $path = $alicos['info']['url'];
        if ($flag == 1) {
            $imgInfo = getimagesize($location);
            $result = array('full_path' => $path, 'path' => substr($path, 51), 'img_width' => $imgInfo[0], 'img_height' => $imgInfo[1]);
        } else {
            $result = array('full_path' => $path, 'path' => substr($path, 51));
        }

        @unlink($location);
        return $result;
    }

    /**
     * 生成GetObject的签名url,主要用于私有权限下的读访问控制
     * @param $object
     * @return null
     */
    public function getSignedUrlForGettingObject($object)
    {
        $timeout = 3600; // URL的有效期是3600秒
        try{
            return $this->ossClient->signUrl($this->bucket, $object, $timeout);
        } catch(OssException $e) {
            return $e->getMessage();
        }

        /**
         * 可以类似的代码来访问签名的URL，也可以输入到浏览器中去访问
         */
/*      $request = new RequestCore($signedUrl);
        $request->set_method('GET');
        $request->send_request();
        $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());

        return $res;*/
    }

    /**
     * 拷贝文件
     * @param $from_bucket
     * @param $from_object
     * @param $to_bucket
     * @param $to_object
     * @return null|string
     */
    function copyObject($from_bucket,$from_object,$to_bucket,$to_object)
    {
        try{
            return $this->ossClient->copyObject($from_bucket, $from_object, $to_bucket, $to_object);
        } catch(OssException $e) {
            return $e->getMessage();
        }
    }

}